<template>
  <div class="maintenance-schedule">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>维护计划</span>
          <div class="header-actions">
            <el-button type="primary" @click="addSchedule">新增计划</el-button>
            <el-button @click="exportSchedule">导出计划</el-button>
          </div>
        </div>
      </template>
      
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-form :model="filterForm" inline>
          <el-form-item label="计划类型">
            <el-select v-model="filterForm.type" placeholder="请选择类型" clearable>
              <el-option label="定期维护" value="定期维护"></el-option>
              <el-option label="预防性维护" value="预防性维护"></el-option>
              <el-option label="专项维护" value="专项维护"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="执行状态">
            <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
              <el-option label="未开始" value="未开始"></el-option>
              <el-option label="进行中" value="进行中"></el-option>
              <el-option label="已完成" value="已完成"></el-option>
              <el-option label="已暂停" value="已暂停"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 计划列表 -->
      <el-table 
        :data="scheduleList" 
        border 
        style="width: 100%"
        v-loading="loading"
        size="small"
      >
        <el-table-column prop="id" label="计划ID" width="70" />
        <el-table-column prop="name" label="计划名称" width="150" show-overflow-tooltip />
        <el-table-column prop="type" label="计划类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)" size="small">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="执行状态" width="80">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="100" />
        <el-table-column prop="endDate" label="结束日期" width="100" />
        <el-table-column prop="frequency" label="执行频率" width="100" />
        <el-table-column prop="maintainer" label="负责人" width="100">
          <template #default="scope">
            {{ getUserName(scope.row.maintainer) }}
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="120">
          <template #default="scope">
            <el-progress 
              :percentage="scope.row.progress" 
              :status="getProgressStatus(scope.row.progress)"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column prop="description" label="计划描述" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <div class="table-actions">
              <div class="action-row">
                <el-button 
                  link 
                  size="small" 
                  @click="viewSchedule(scope.row)"
                >
                  查看
                </el-button>
                <el-button 
                  link 
                  size="small" 
                  @click="editSchedule(scope.row)"
                  :disabled="scope.row.status === '已完成'"
                >
                  编辑
                </el-button>
              </div>
              <div class="action-row">
                <el-button 
                  link 
                  size="small" 
                  @click="startSchedule(scope.row)"
                  v-if="scope.row.status === '未开始'"
                >
                  开始
                </el-button>
                <el-button 
                  link 
                  size="small" 
                  @click="pauseSchedule(scope.row)"
                  v-if="scope.row.status === '进行中'"
                >
                  暂停
                </el-button>
                <el-button 
                  link 
                  size="small" 
                  @click="deleteSchedule(scope.row)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑计划对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="resetForm"
    >
      <el-form :model="scheduleForm" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划名称" prop="name">
              <el-input v-model="scheduleForm.name" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划类型" prop="type">
              <el-select v-model="scheduleForm.type" placeholder="请选择类型">
                <el-option label="定期维护" value="定期维护"></el-option>
                <el-option label="预防性维护" value="预防性维护"></el-option>
                <el-option label="专项维护" value="专项维护"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="scheduleForm.startDate"
                type="date"
                placeholder="选择开始日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="scheduleForm.endDate"
                type="date"
                placeholder="选择结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="执行频率" prop="frequency">
              <el-select v-model="scheduleForm.frequency" placeholder="请选择频率">
                <el-option label="每日" value="每日"></el-option>
                <el-option label="每周" value="每周"></el-option>
                <el-option label="每月" value="每月"></el-option>
                <el-option label="每季度" value="每季度"></el-option>
                <el-option label="每年" value="每年"></el-option>
                <el-option label="一次性" value="一次性"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="maintainer">
              <el-select v-model="scheduleForm.maintainer" placeholder="请选择负责人">
                <el-option
                  v-for="user in userOptions"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="计划描述" prop="description">
          <el-input
            v-model="scheduleForm.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述维护计划内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="提醒设置">
          <el-checkbox-group v-model="scheduleForm.reminders">
            <el-checkbox value="email">邮件提醒</el-checkbox>
            <el-checkbox value="sms">短信提醒</el-checkbox>
            <el-checkbox value="system">系统提醒</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 计划详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="维护计划详情"
      width="800px"
    >
      <div v-if="selectedSchedule" class="schedule-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="计划名称">
            {{ selectedSchedule.name }}
          </el-descriptions-item>
          <el-descriptions-item label="计划类型">
            <el-tag :type="getTypeTagType(selectedSchedule.type)">
              {{ selectedSchedule.type }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="执行状态">
            <el-tag :type="getStatusTagType(selectedSchedule.status)">
              {{ selectedSchedule.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="执行频率">
            {{ selectedSchedule.frequency }}
          </el-descriptions-item>
          <el-descriptions-item label="开始日期">
            {{ selectedSchedule.startDate }}
          </el-descriptions-item>
          <el-descriptions-item label="结束日期">
            {{ selectedSchedule.endDate }}
          </el-descriptions-item>
          <el-descriptions-item label="负责人">
            {{ getUserName(selectedSchedule.maintainer) }}
          </el-descriptions-item>
          <el-descriptions-item label="进度">
            <el-progress 
              :percentage="selectedSchedule.progress" 
              :status="getProgressStatus(selectedSchedule.progress)"
            />
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ selectedSchedule.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ selectedSchedule.updateTime }}
          </el-descriptions-item>
          <el-descriptions-item label="计划描述" :span="2">
            {{ selectedSchedule.description || '暂无描述' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 执行记录 -->
        <div class="execution-records">
          <h4>执行记录</h4>
          <el-table :data="selectedSchedule.executionRecords || []" size="small">
            <el-table-column prop="date" label="执行日期" width="120" />
            <el-table-column prop="status" label="执行状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'" size="small">
                  {{ scope.row.status === 'success' ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="executor" label="执行人" width="100" />
            <el-table-column prop="result" label="执行结果" />
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </div>
        
        <!-- 操作按钮 -->
        <div class="detail-actions">
          <el-button type="primary" @click="editSchedule(selectedSchedule)">
            编辑计划
          </el-button>
          <el-button 
            type="success" 
            @click="startSchedule(selectedSchedule)"
            v-if="selectedSchedule.status === '未开始'"
          >
            开始执行
          </el-button>
          <el-button 
            type="warning" 
            @click="pauseSchedule(selectedSchedule)"
            v-if="selectedSchedule.status === '进行中'"
          >
            暂停执行
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, type Ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { maintenancePlanApi, userApi } from '@/api'

const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()

// 筛选表单
const filterForm = reactive({
  type: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = ref({
  current: 1,
  size: 20,
  total: 0
})

// 计划表单
const scheduleForm = reactive({
  id: '',
  name: '',
  type: '',
  startDate: '',
  endDate: '',
  frequency: '',
  maintainer: '',
  description: '',
  reminders: []
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入计划名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择计划类型', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ],
  frequency: [
    { required: true, message: '请选择执行频率', trigger: 'change' }
  ],
  maintainer: [
    { required: true, message: '请选择负责人', trigger: 'change' }
  ]
}

// 计划列表数据（后端拉取）
interface Schedule {
  id: number;
  name: string;
  type: string;
  status: string;
  startDate: string;
  endDate: string;
  frequency: string;
  maintainer: string;
  progress: number;
  description: string;
  createTime?: string;
  updateTime?: string;
  executionRecords?: any[];
}

const scheduleList = ref<Schedule[]>([]) as Ref<Schedule[]>

const userOptions = ref<any[]>([])

const getUserName = (id: number | string) => {
  const user = userOptions.value.find((u:any) => u.id === id)
  return user ? user.name : id
}

const loadUsers = async () => {
  try {
    const res:any = await userApi.getAll()
    userOptions.value = res.list || res || []
  } catch (e) {
    console.error('加载用户失败', e)
  }
}

const dialogTitle = computed(() => isEdit.value ? '编辑计划' : '新增计划')

const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    '定期维护': 'primary',
    '预防性维护': 'success',
    '专项维护': 'warning'
  }
  return typeMap[type] || 'info'
}

const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    '未开始': 'info',
    '进行中': 'warning',
    '已完成': 'success',
    '已暂停': 'danger'
  }
  return statusMap[status] || 'info'
}

const getProgressStatus = (progress: number) => {
  if (progress === 100) return 'success'
  if (progress >= 80) return 'warning'
  return ''
}

const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

const resetFilter = () => {
  filterForm.type = ''
  filterForm.status = ''
  filterForm.dateRange = []
  handleSearch()
}

const loadData = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.value.current,
      size: pagination.value.size,
      type: filterForm.type,
      status: filterForm.status ? scheduleStatusCode[filterForm.status] : undefined,
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1]
    }
    const res: any = await maintenancePlanApi.getList(params)
    const rows = res.list || res.records || []
    scheduleList.value = rows.map((r:any)=> ({
      ...r,
      startDate: r.planStart,
      endDate: r.planEnd,
      // 后端状态为数字，转换为中文文本
      status: scheduleStatusText[r.status] ?? '未开始'
    }))
    pagination.value.total = res.total || 0
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (size: number) => {
  pagination.value.size = size
  loadData()
}

const handleCurrentChange = (current: number) => {
  pagination.value.current = current
  loadData()
}

const addSchedule = () => {
  isEdit.value = false
  dialogVisible.value = true
}

const editSchedule = (row: any) => {
  isEdit.value = true
  Object.assign(scheduleForm, row)
  dialogVisible.value = true
}

const viewSchedule = (row: any) => {
  selectedSchedule.value = row
  detailDialogVisible.value = true
}

const startSchedule = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要开始执行计划"${row.name}"吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    await maintenancePlanApi.updateStatus(row.id, 1, 0)
    row.status = '进行中'
    ElMessage.success('计划已开始执行')
  } catch {
    // 用户取消
  }
}

const pauseSchedule = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要暂停计划"${row.name}"吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await maintenancePlanApi.updateStatus(row.id, 3, row.progress)
    row.status = '已暂停'
    ElMessage.success('计划已暂停')
  } catch {
    // 用户取消
  }
}

const deleteSchedule = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除计划"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await maintenancePlanApi.delete(row.id)
    scheduleList.value = scheduleList.value.filter(s => s.id !== row.id)
    ElMessage.success('删除成功')
  } catch {
    // 用户取消
  }
}

const exportSchedule = () => {
  // 创建CSV内容
  const headers = ['计划ID', '计划名称', '计划类型', '执行状态', '开始日期', '结束日期', '执行频率', '负责人', '进度', '描述']
  const csvContent = [
    headers.join(','),
    ...scheduleList.value.map((schedule: Schedule) => [
      schedule.id,
      schedule.name,
      schedule.type,
      schedule.status,
      schedule.startDate,
      schedule.endDate,
      schedule.frequency,
      schedule.maintainer,
      schedule.progress + '%',
      schedule.description || ''
    ].join(','))
  ].join('\n')
  
  // 创建下载链接
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', `维护计划_${new Date().toISOString().split('T')[0]}.csv`)
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('维护计划导出成功')
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 组装请求数据，字段需与后端保持一致
    const payload: any = {
      name: scheduleForm.name,
      type: scheduleForm.type,
      planStart: scheduleForm.startDate,
      planEnd: scheduleForm.endDate,
      frequency: scheduleForm.frequency,
      maintainer: scheduleForm.maintainer,
      description: scheduleForm.description
    }

    if (isEdit.value && scheduleForm.id) {
      // 更新
      await maintenancePlanApi.update(scheduleForm.id, payload)
      ElMessage.success('计划更新成功')
    } else {
      // 新增
      await maintenancePlanApi.add(payload)
      ElMessage.success('计划创建成功')
    }

    dialogVisible.value = false
    resetForm()
    loadData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  Object.assign(scheduleForm, {
    id: '',
    name: '',
    type: '',
    startDate: '',
    endDate: '',
    frequency: '',
    maintainer: '',
    description: '',
    reminders: []
  })
}

const selectedSchedule = ref<Schedule | null>(null)
const detailDialogVisible = ref(false)

// 状态映射（计划）：0 未开始 1 进行中 2 已完成 3 已暂停
const scheduleStatusCode: Record<string, number> = {
  '未开始': 0,
  '进行中': 1,
  '已完成': 2,
  '已暂停': 3
}

const scheduleStatusText: Record<number, string> = {
  0: '未开始',
  1: '进行中',
  2: '已完成',
  3: '已暂停'
}

onMounted(() => {
  loadUsers()
  loadData()
})
</script>

<style scoped>
.maintenance-schedule {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格操作按钮样式优化 */
.table-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.action-row {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.action-row .el-button {
  padding: 4px 6px;
  font-size: 12px;
  min-width: auto;
}

/* 表格响应式优化 */
@media (max-width: 1200px) {
  .action-row {
    flex-direction: column;
    gap: 2px;
  }
  
  .action-row .el-button {
    padding: 2px 4px;
    font-size: 11px;
  }
}

@media (max-width: 768px) {
  .maintenance-schedule {
    padding: 10px;
  }
  
  .filter-section {
    padding: 15px;
  }
  
  .filter-section .el-form {
    display: flex;
    flex-direction: column;
  }
  
  .filter-section .el-form-item {
    margin-bottom: 10px;
  }
  
  .header-actions {
    flex-direction: column;
  }
  
  /* 移动端表格优化 */
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table th),
  :deep(.el-table td) {
    padding: 8px 4px;
  }
}
</style> 